package com.azure.bigstore.controller;

import com.azure.bigstore.entity.Product;
import com.azure.bigstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuhuaibin on 2018/1/22.
 */
@RestController
@RequestMapping("/v1")
public class SearchController {

    @Autowired
    private ProductService productService;

    private static List<Product> list = new ArrayList<>();
    private static int n = 10;

    /**
     * search product
     * @param keyword 产品title关键字
     * @param ptype 产品类别
     * @return List<Product>
     */
    @PostMapping("/search")
    public List<Product> doSearch(@RequestParam String keyword, @RequestParam String ptype){
        System.out.println("==keyword:"+keyword+" ==ptype:"+ptype);
        List<Product> list = new ArrayList<>();
        //只根据关键字查询。类别为空
        if(ptype == null || "".equals(ptype) ) {
            list = productService.searchProductsByKeyword(keyword);
            return list;

        //只根据类别查询。关键字为空
        }else if(keyword == null || "".equals(keyword)){
            list = productService.searchProductsByCategory(ptype);
            return list;

        //根据类别和关键字查询
        }else{
            list = productService.searchProducts(ptype,keyword);
            System.out.println("search_list:"+list);
            return list;
        }
    }

    /**
     * 分页
     * @param page 页码
     * @return List<Product>
     */
    @GetMapping("/search")
    public List<Product> doSearch(@RequestParam String page){
        System.out.println("==paeg:"+page +" ==list.size:"+list.size());

        List<Product> pagelist = new ArrayList<>();
        if(list.size()>0 && (page !=null && !"".equals(page)) ){
            int index = (Integer.valueOf(page)-1) < 0 ? 0 : (Integer.valueOf(page)-1);
            if(list.size() >= (n * (index+1)) )
                pagelist = list.subList( n * index, n * (index+1) );
            else
                pagelist = list.subList(n * index, list.size());
        }
        return pagelist;
    }
}
